package uk.co.BexhillWeb.MediaManager.PluginSystem;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.logging.Logger;

import uk.co.BexhillWeb.MediaManager.EventUtilities.CustomEvent;
import uk.co.BexhillWeb.MediaManager.Managers.EventManager;
import uk.co.BexhillWeb.MediaManager.Managers.WindowManager;
import uk.co.BexhillWeb.PluginApi.IPlugin;
 
public class StandardPluginService implements PluginInterface
{
    private static StandardPluginService pluginService;
    private ServiceLoader<IPlugin> serviceLoader;
    private Logger logger = Logger.getLogger(getClass().getName());
 
    private StandardPluginService()
    {
        //load all the classes in the classpath that have implemented the interface
        serviceLoader = ServiceLoader.load(IPlugin.class);
    }
 
    public static StandardPluginService getInstance()
    {
        if(pluginService == null)
            pluginService = new StandardPluginService();
        return pluginService;
    }
 
    public Iterator<IPlugin> getPlugins()
    {
        return serviceLoader.iterator();
    }
 
    public void initPlugins()
    {
        Iterator<IPlugin> iterator = getPlugins();
        if(!iterator.hasNext())
        {
            logger.info("No plugins were found!");
        }
        while(iterator.hasNext())
        {
        	IPlugin plugin = iterator.next();
            logger.info("Initializing the plugin " + plugin.getName());
            
            plugin.init();
            if(plugin.getPluginType().equals("WINDOWPANEL")){
            	logger.info("found window panel!");
            	WindowManager.addWindow(plugin.getWindow());
            }
            EventManager.fireMyEvent(new CustomEvent(StandardPluginService.class));
            
            //switch(plugin.getPluginType()){
            //case WINDOWPANEL: WindowManager.addWindow(plugin.getWindow()); break;
            //case BACKGROUND: ; break;
            //}
        }
    }
}
